import { View, Text, Button } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { voiceDebugger } from '../../utils/voiceDebugger'
import { voicePlayerManager } from '../../utils/voicePlayer'

import './voice-test.scss'

export default function VoiceTest() {
  useLoad(() => {
    console.log('语音测试页面加载')
  })

  const [testUrl, setTestUrl] = useState('https://www.soundjay.com/misc/sounds/bell-ringing-05.wav')
  const [debugInfo, setDebugInfo] = useState<any>(null)
  const [testResult, setTestResult] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(false)

  // 收集调试信息
  const collectDebugInfo = async () => {
    setIsLoading(true)
    try {
      const info = await voiceDebugger.collectDebugInfo()
      setDebugInfo(info)
      console.log('调试信息收集完成:', info)
    } catch (error) {
      console.error('收集调试信息失败:', error)
      Taro.showToast({ title: '收集调试信息失败', icon: 'none' })
    } finally {
      setIsLoading(false)
    }
  }

  // 测试语音播放
  const testVoicePlayback = async () => {
    if (!testUrl) {
      Taro.showToast({ title: '请输入测试URL', icon: 'none' })
      return
    }

    setIsLoading(true)
    try {
      const result = await voiceDebugger.testVoicePlayback(testUrl)
      setTestResult(result)
      console.log('语音播放测试结果:', result)
      
      if (result.success) {
        Taro.showToast({ title: '语音播放测试成功', icon: 'success' })
      } else {
        Taro.showToast({ 
          title: `测试失败: ${result.error}`, 
          icon: 'none',
          duration: 3000
        })
      }
    } catch (error) {
      console.error('语音播放测试失败:', error)
      Taro.showToast({ title: '测试失败', icon: 'none' })
    } finally {
      setIsLoading(false)
    }
  }

  // 使用语音播放器测试
  const testWithVoicePlayer = async () => {
    if (!testUrl) {
      Taro.showToast({ title: '请输入测试URL', icon: 'none' })
      return
    }

    setIsLoading(true)
    try {
      await voicePlayerManager.play('test-player', testUrl, {
        onPlay: () => {
          console.log('播放开始')
          Taro.showToast({ title: '播放开始', icon: 'success' })
        },
        onError: (error) => {
          console.error('播放错误:', error)
          Taro.showToast({ title: `播放错误: ${error}`, icon: 'none' })
        },
        onEnded: () => {
          console.log('播放结束')
          Taro.showToast({ title: '播放结束', icon: 'success' })
        }
      })
    } catch (error) {
      console.error('语音播放器测试失败:', error)
      Taro.showToast({ title: '播放器测试失败', icon: 'none' })
    } finally {
      setIsLoading(false)
    }
  }

  // 生成调试报告
  const generateReport = () => {
    if (!debugInfo) {
      Taro.showToast({ title: '请先收集调试信息', icon: 'none' })
      return
    }

    const report = voiceDebugger.generateDebugReport()
    console.log('调试报告:', report)
    
    Taro.setClipboardData({
      data: report,
      success: () => {
        Taro.showToast({ title: '调试报告已复制到剪贴板', icon: 'success' })
      }
    })
  }

  return (
    <View className='voice-test-container'>
      <View className='header'>
        <Text className='title'>语音播放测试</Text>
        <Text className='subtitle'>调试语音播放问题</Text>
      </View>

      <View className='test-section'>
        <View className='input-group'>
          <Text className='label'>测试音频URL:</Text>
          <View className='input-container'>
            <input
              className='url-input'
              value={testUrl}
              onChange={(e) => setTestUrl(e.target.value)}
              placeholder='请输入音频文件URL'
            />
          </View>
        </View>

        <View className='button-group'>
          <Button 
            className='test-button'
            onClick={collectDebugInfo}
            loading={isLoading}
          >
            收集调试信息
          </Button>
          
          <Button 
            className='test-button'
            onClick={testVoicePlayback}
            loading={isLoading}
          >
            测试语音播放
          </Button>
          
          <Button 
            className='test-button'
            onClick={testWithVoicePlayer}
            loading={isLoading}
          >
            使用播放器测试
          </Button>
        </View>
      </View>

      {debugInfo && (
        <View className='debug-section'>
          <Text className='section-title'>调试信息</Text>
          <View className='debug-info'>
            <Text className='info-item'>平台: {debugInfo.platform}</Text>
            <Text className='info-item'>设备: {debugInfo.deviceInfo?.model || '未知'}</Text>
            <Text className='info-item'>网络: {debugInfo.networkStatus?.networkType || '未知'}</Text>
            <Text className='info-item'>音频上下文: {debugInfo.audioContext?.created ? '正常' : '异常'}</Text>
            <Text className='info-item'>音量: {debugInfo.audioContext?.volume || '未知'}</Text>
            <Text className='info-item'>静音开关: {debugInfo.audioContext?.obeyMuteSwitch ? '遵循' : '忽略'}</Text>
          </View>
          
          <Button 
            className='report-button'
            onClick={generateReport}
          >
            生成调试报告
          </Button>
        </View>
      )}

      {testResult && (
        <View className='result-section'>
          <Text className='section-title'>测试结果</Text>
          <View className='test-result'>
            <Text className='result-item'>状态: {testResult.success ? '成功' : '失败'}</Text>
            {testResult.error && (
              <Text className='result-item error'>错误: {testResult.error}</Text>
            )}
            {testResult.details?.eventLog && (
              <Text className='result-item'>事件数量: {testResult.details.eventLog.length}</Text>
            )}
            {testResult.details?.finalState && (
              <View className='final-state'>
                <Text className='state-item'>时长: {testResult.details.finalState.duration || '未知'}</Text>
                <Text className='state-item'>当前时间: {testResult.details.finalState.currentTime || '未知'}</Text>
                <Text className='state-item'>暂停状态: {testResult.details.finalState.paused ? '是' : '否'}</Text>
              </View>
            )}
          </View>
        </View>
      )}

      <View className='tips-section'>
        <Text className='section-title'>调试提示</Text>
        <View className='tips'>
          <Text className='tip-item'>• 确保设备音量已开启</Text>
          <Text className='tip-item'>• 检查设备是否处于静音模式</Text>
          <Text className='tip-item'>• 确保音频文件URL有效且可访问</Text>
          <Text className='tip-item'>• 在真机上测试，开发者工具可能有限制</Text>
          <Text className='tip-item'>• 检查网络连接状态</Text>
        </View>
      </View>
    </View>
  )
}
